﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Imaging;
using System.Net.Sockets;
using System.Net;
using Model;
using GameHelp;
using Intorise.Tools.Process;

namespace TdyxAutoBot
{
    /// <summary>
    /// 登录完毕
    /// </summary>
    /// <param name="message">登录相关信息</param>
    /// <param name="sucess">登录是否成功</param>
    public delegate void LoginCompletedDelegate(bool sucess, string message);

    public partial class ClientForm : Form
    {
        private Uri loginUri = new Uri("http://www.6711.com/login.html?forward=%2Fentergame.php%3Fgame%3Dtdyx%26server%3DS5");
        private Uri gameLogoutUri = new Uri("http://s5.tdyx.6711.com/logout");
        private Uri websiteLogoutUri = new Uri("http://www.6711.com/login.html?do=logout");
        private Uri gameUri = new Uri("http://s5.tdyx.6711.com/");
        private Account currentAccount = null;
        private const int SleepTime = 1000;//操作后的等待时间单位：毫秒，如果网络不好或者电脑性能低则增大，超时时间过后将重新登录游戏
        ManualResetEvent logoutEvent = new ManualResetEvent(true);//用于等待退出的标识
        private string autoGameWindowName = "";//助手程序的窗口名称
        private string accountInfoMessage;//用于发送消息时标识账户
        private bool logined = false;//是否已登录
        ParameterizedThreadStart loginThreadStart =null;//登录线程
        WebBrowserDocumentCompletedEventHandler loginPageCompletedHandler = null;
        WebBrowserDocumentCompletedEventHandler gamePageCompletedHandler = null;
        WebBrowserDocumentCompletedEventHandler gameLogoutCompletedHandler = null;
        WebBrowserDocumentCompletedEventHandler websiteLogoutCompletedHandler = null;
        List<Account> accountList = new List<Account>();

        public ClientForm()
        {
            Form.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

            //accountList.Add(new Account("test123456", "test123456"));
            //accountList.Add(new Account("test123457", "test123456"));
            //accountList.Add(new Account("test123458", "test123456"));
            //accountList.Add(new Account("test123459", "test123456"));
            //accountList.Add(new Account("test123460", "test123456"));
            //accountList.Add(new Account("test123461", "test123456"));
            //accountList.Add(new Account("test123468", "123456"));
            //accountList.Add(new Account("test123469", "123456"));
            //accountList.Add(new Account("test123472", "123456"));
            //accountList.Add(new Account("test123475", "123456"));//yyao7716
            //accountList.Add(new Account("yyao7716", "770106ok"));//霸天，安全密码6611
            //accountList.Add(new Account("yyao7176", "770106ok"));//雾非
            foreach (Account a in Manager.AccountList)
            {
                this.cbxAccount.Items.Add(a);
            }

            loginThreadStart = new ParameterizedThreadStart(NewLogin);//登录线程
            loginPageCompletedHandler = new WebBrowserDocumentCompletedEventHandler(webBrowser1_loginPageCompleted);
            gamePageCompletedHandler = new WebBrowserDocumentCompletedEventHandler(webBrowser1_gamePageCompleted);
            gameLogoutCompletedHandler = new WebBrowserDocumentCompletedEventHandler(webBrowser1_gameLogoutPageCompleted);
            websiteLogoutCompletedHandler = new WebBrowserDocumentCompletedEventHandler(webBrowser1_WebsiteLogoutCompleted);
            //this.webBrowser1.DocumentCompleted += loginPageCompletedHandler;
        }

        /// <summary>
        /// 使用给定账户信息打开窗口
        /// </summary>
        /// <param name="account">账户</param>
        /// <param name="state">成功登录后客户端窗口的状态</param>
        public void Show(Account account, ClientWindowState state)
        {
            this.Show();
            this.currentAccount = account;
            this.webBrowser1.DocumentCompleted += this.webBrowser1_loginPageCompleted;
            this.webBrowser1.Navigate(loginUri);
        }

        /// <summary>
        /// 登录程序执行完毕时发生
        /// </summary>
        public event LoginCompletedDelegate OnLoginCompleted;

        //登录页面加载完成
        private void webBrowser1_loginPageCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                this.webBrowser1.DocumentCompleted -= loginPageCompletedHandler;
                this.webBrowser1.Document.All["username"].SetAttribute("value", currentAccount.Username);
                this.webBrowser1.Document.All["password"].SetAttribute("value", currentAccount.Password);
                this.webBrowser1.Document.Forms[0].InvokeMember("submit");
                Thread.Sleep(SleepTime);
                //CapateNetpacket();
                this.webBrowser1.DocumentCompleted += gamePageCompletedHandler;
                this.webBrowser1.Navigate(gameUri);
            }
        }

        //游戏页面加载完成
        private void webBrowser1_gamePageCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                if (this.webBrowser1.Document.Body.InnerText.IndexOf("您输入了错误的密码！") > -1)
                {
                    if (OnLoginCompleted != null)
                    {
                        //Console.WriteLine("账户：" + currentAccount.Username + "的密码错误。");
                        OnLoginCompleted(false, "账户：" + currentAccount.Username + "的密码错误。");
                    }
                    ProcessMessage.SendMessage(autoGameWindowName, "Login\tfalse\t账户：" + currentAccount.Username + " 的密码错误");
                    return;
                }
                ProcessMessage.SendMessage(autoGameWindowName, "Login\ttrue\t账户：" + currentAccount.Username + " 成功登录");
                this.webBrowser1.Document.InvokeScript("CloseFrm");
                this.webBrowser1.DocumentCompleted -= gamePageCompletedHandler;

                if (OnLoginCompleted != null)
                {
                    //Console.WriteLine("账户：" + currentAccount.Username + "的密码错误。");
                    OnLoginCompleted(true, "账户：" + currentAccount.Username + "登录成功。");
                }
                logined = true;
            }
        }

        //游戏退出页面加载完成
        private void webBrowser1_gameLogoutPageCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                this.webBrowser1.DocumentCompleted -= gameLogoutCompletedHandler;
                this.webBrowser1.DocumentCompleted += websiteLogoutCompletedHandler;
                this.webBrowser1.Navigate(websiteLogoutUri);//网站退出
            }
        }

        //网站退出页面加载完成
        void webBrowser1_WebsiteLogoutCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                logined = false;
                logoutEvent.Set();
                this.webBrowser1.DocumentCompleted -= websiteLogoutCompletedHandler;
                ProcessMessage.SendMessage(autoGameWindowName, "Logout\ttrue\t账户：" + currentAccount.Username + " 已退出");
            }
        }

        //退出
        private void Logout()
        {
            logoutEvent.Reset();
            this.webBrowser1.DocumentCompleted -= gamePageCompletedHandler;
            this.webBrowser1.DocumentCompleted -= loginPageCompletedHandler;

            this.webBrowser1.DocumentCompleted += gameLogoutCompletedHandler;
            this.webBrowser1.Navigate(gameLogoutUri);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Logout();
        }

        //登录
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (this.cbxAccount.SelectedItem != null)
            {
                this.currentAccount = (Account)this.cbxAccount.SelectedItem;
                this.webBrowser1.DocumentCompleted += this.webBrowser1_loginPageCompleted;
                this.webBrowser1.Navigate(loginUri);
            }
        }

        //暂停
        private void btnPauseGame_Click(object sender, EventArgs e)
        {
            ProcessMessage.SendMessage(autoGameWindowName, "Pause\t" + accountInfoMessage);
        }

        //继续
        private void btnResumeGame_Click(object sender, EventArgs e)
        {
            ProcessMessage.SendMessage(autoGameWindowName, "Continue\t" + accountInfoMessage);
        }

        //终止当前任务
        private void btnStop_Click(object sender, EventArgs e)
        {
            ProcessMessage.SendMessage(autoGameWindowName, "Stop\t" + accountInfoMessage);
        }

        //终止所有任务
        private void btnStopAll_Click(object sender, EventArgs e)
        {
            ProcessMessage.SendMessage(autoGameWindowName, "StopAll\t" + accountInfoMessage);
        }

        protected override void DefWndProc(ref Message m)
        {
            string message = "";
            ProcessMessage.ReadMessage(ref m, ref message);
            if (!string.IsNullOrEmpty(message))
            {
                string[] code = message.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                if (code.Length > 0)
                {
                    switch (code[0])
                    {
                        case "Login"://接到登录账户的命令
                            break;
                        case "Logined"://接到助手已登录信息
                            currentAccount.Character = new Characters(code[1]);
                            break;
                        case "NeedHide"://接到隐藏窗口的命令
                            this.Hide();
                            break;
                        case "NeedShow"://接到显示窗口的命令
                            this.Show();
                            break;
                        case "NeedExit"://接到退出的命令
                            Application.Exit();
                            break;
                        case "ReLogin"://接到重新登录的命令，刷新页面
                            this.webBrowser1.Refresh();
                            break;
                        case "Logout"://接到退出当前账户的命令
                            Logout();
                            break;
                    }
                }
            }
            base.DefWndProc(ref m);
        }

        private void ClientForm_Load(object sender, EventArgs e)
        {
            //有参数，通过助手启动，获取助手窗口名称和要启动的账户信息
            if (Program.Args.Length > 0)
            {
                autoGameWindowName = Program.Args[0];//助手窗口标题
                currentAccount = new Account();
                currentAccount.Username = Program.Args[1];//账户
                currentAccount.Password = Program.Args[2];//密码                
                currentAccount.Character = new Characters(Program.Args[3]);//角色名
                currentAccount.Chanel = Program.Args[4];//平台
                currentAccount.ServerID = Program.Args[5];//服务器编号

                accountInfoMessage = currentAccount.Chanel + "\t" + currentAccount.ServerID + "\t" +
                    currentAccount.Username + "\t" + currentAccount.Character.Name;

                this.Text = currentAccount.Chanel+" "+currentAccount.ServerID+" "+currentAccount.Username + " " +currentAccount.Character.Name+" "+ DateTime.Now.ToLongTimeString();
                ProcessMessage.SendMessage(autoGameWindowName, "Start\t" + this.Text);//发送成功启动的消息
                this.webBrowser1.DocumentCompleted += this.webBrowser1_loginPageCompleted;
                this.webBrowser1.Navigate(loginUri);
            }
        }

        //选中下拉框直接登录
        private void cbxAccount_SelectedIndexChanged(object sender, EventArgs e)
        {
            Thread thread = new Thread(loginThreadStart);
            thread.Start();
        }

        //登录
        private void NewLogin(object o)
        {
            if (logined)
            {
                Logout();
                logoutEvent.WaitOne();//等待上一个账户退出
            }

            btnLogin_Click(null, null);
        }
    }
}
